import { useParams } from "react-router-dom";
import { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import { Top } from "../components/top/Top";
import Bottom from "../components/bottom/Bottom";
import "./Product.css";
import { productService } from "../../service/productService";
import { common_utils } from "../../utils/utils";

export default function Product() {
    const { categoryId } = useParams(); 
    const [products, setProducts] = useState([]);
    const [loading, setLoading] = useState(true);
  
    useEffect(() => {
      if (!categoryId) return; 
  
      setLoading(true);
      productService.getProducts(categoryId, (response) => {
        setProducts(response.data || []);
        setLoading(false);
      });
    }, [categoryId]);

    return (
        <>
            <Top />
            <div className="product-container">
                <div className="product-header">
                    <h2>{categoryId}</h2>
                </div>


                {loading ? (
                    <p>Loading products...</p>
                ) : (
                    <ProductsTable products={products} />
                )}
            </div>
            <Bottom />
        </>
    );
}


function ProductsTable({ products }){
    const onClick= (product) => {
        window.location.href = `/products/${product.productid}/items`;
    }



    return(

        <table className="product-table">
        <thead>
            <tr>
                <th>Product ID</th>
                <th>Name</th>
                <th>Description</th>
                <th>Preview</th>
            </tr>
        </thead>
        <tbody>
            {products.map((product, index) => (
                <tr onClick={() => onClick(product)} key={index}>
                    <td>{product.productid}</td>
                    <td>{product.name}</td>
                    <td>{product.description}</td>
                    <td>
                        {/* 使用预加载的图片资源 */}
                        <img
                            src={common_utils.getServerImageURL(product.image)}
                            alt={product.name}
                            className="product-preview"
                        />
                    </td>
                </tr>
            ))}
        </tbody>
    </table>

    )
}